<template>
  <view class="page">
    <view v-if="$data.info">
      <view class="status" :style="[$data.info._config.style]">
        {{ $data.info._config.label }}
      </view>
      <!-- 基本信息 -->
      <view class="card margin-top">
        <!-- <view class="row">
          <view class="row_left">实付金额</view>
          <view class="row_right">{{ $data.info.orderTotalPrice }}</view>
        </view> -->
        <view class="row">
          <view class="row_left">退款金额</view>
          <view class="row_right">{{ $data.info.orderRefundPrice }}</view>
        </view>
        <view v-if="$data.info.workSecondPrice > 0" class="red">
          *因保洁师已上门后取消订单，需扣除
          {{ $data.info.workSecondPrice }}
          元上门费
        </view>
        <view class="row">
          <view class="row_left">退款渠道</view>
          <view class="row_right">{{ $data.info._wayConfig.label }}</view>
        </view>
        <!-- <view class="row">
          <view class="row_left">加急退款</view>
          <view class="row_right">{{ $data.info.fastRefundPrice }}</view>
        </view>
        <view class="row">
          <view class="row_left">退款渠道</view>
          <view class="row_right">{{ $data.info._wayJJConfig.label }}</view>
        </view> -->
      </view>
      <!-- 优惠券 -->
      <!-- <view class="card margin-top" v-if="$data.info.coupon.length > 0">
        <view class="row margin-bottom">
          <view class="row_left">退优惠券</view>
        </view>
        <view
          class="list-item"
          v-for="(item, index) of $data.info.coupon"
          :key="index"
        >
          <view class="coupon">
            <view class="left_img">
              <image :src="ImgCouponLeftGreen" />
              <view class="left_img--text">
                <view
                  class="price text-center"
                  :class="[
                    { 'text-price': item.couponType == couponType.money },
                  ]"
                >
                  {{ item.actualPrice }}
                  <text v-if="item.couponType == couponType.discount">折</text>
                </view>
                <view class="margin-top-xs desc u-line-1">
                  满
                  {{ item.fullPrice }}
                  元可用
                </view>
              </view>
            </view>
            <view class="right">
              <view class="right_title">
                <text v-if="item._couponTypeName">
                  【{{ item._couponTypeName }}】
                </text>
                <text>
                  {{ item.title }}
                </text>
              </view>
              <view class="right_time text-wrap">
                <text v-if="item.validityType == couponWellType.today">
                  领取后{{ item.validDays }}天内有效
                </text>
                <text v-else-if="item.validityType == couponWellType.date">
                  可预约{{ item.startTime }}至{{ item.endTime }}的服务
                </text>
              </view>
              <view class="right_btn" @tap="onOpen(item)">
                <view class="margin-right-xs">使用说明</view>
                <up-icon
                  :name="item._open ? 'arrow-up' : 'arrow-down'"
                  :color="BasicConfig.MainColor"
                ></up-icon>
              </view>
            </view>
          </view>
          <view v-if="item._open" class="coupon-desc">
            <view class="desc_row">
              1.限用服务：{{ item.domesticServiceTitle }}
            </view>
            <view class="desc_row margin-tb">
              2.限用城市：{{ item.useCity }}
            </view>
            <view class="desc_row"> 3.限用日期：{{ item._useDate }} </view>
          </view>
        </view>
      </view> -->
      <!-- 审批流 -->
      <view class="examine">
        <view
          v-for="(item, index) of $data.info.auditJson"
          :key="index"
          :id="`item_${index}`"
        >
          <view class="dot">
            <view
              class="dot_left"
              :class="[
                {
                  'dot_left--active': index === 0,
                },
              ]"
            >
            </view>
            <view class="dot_right">
              <view class="margin-left-sm content">
                <view class="flex justify-between align-center">
                  <view class="u-line-1">{{ item.title }}</view>
                  <view class="text-gray text-df">{{ item.createAt }}</view>
                </view>
                <view class="margin-top text-df">
                  {{ item.content }}
                </view>
              </view>
            </view>
          </view>
          <view v-if="index < $data.info.auditJson.length - 1" class="gap">
            <view class="gap_left"></view>
            <view class="gap_right"></view>
          </view>
        </view>
        <!-- </view> -->
      </view>
      <!-- 底部按钮 -->
      <view class="foot foot_box">
        <!-- <view
          v-if="
            [orderRefundStatus.can, orderRefundStatus.await].includes(
              $data.info.refundStatus
            )
          "
          class="btn btn_save"
          @tap="onCancel"
        >
          取消售后
        </view> -->
        <!-- v-else -->
        <view class="btn btn_save" @tap="() => ($data.csphoneShow = true)">
          联系客服
        </view>
        <!-- <view class="btn btn_save" v-if="showApplyBtn" @tap="onSave">
          确认提交
        </view> -->
      </view>
    </view>
    <PopupCSPhone v-model:show="$data.csphoneShow" title="官方客服电话" />
    <PopupLogin />
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, nextTick, computed } from "vue";
import { onLoad, onShow, onHide, onReady, onUnload } from "@dcloudio/uni-app";
import {
  cancelRefundOrder,
  cancelSubscribeOrder,
  getOrderDetail,
  refundOrderDetail,
} from "../../../../api/Interface/order";
import errorCode from "../../../../utils/http/errorCode";
import { isDev } from "../../../../utils/env";
import BasicConfig from "../../../../utils/config";
import { jumpPage } from "../../../../utils/route/route";
import { ImgCouponLeftGreen } from "../../../../utils/iconMap";
import {
  orderRefundStatus,
  orderRefundStatusConfig,
  orderRefundWayConfig,
  orderStatus,
} from "../../../../enums/order";
import {
  couponType,
  couponTypeConfig,
  couponUseTypeConfig,
  couponWellType,
} from "../../../../enums/coupon";
import PopupCSPhone from "../../../../components/PopupCSPhone.vue";
import { useImgSrc } from "../../../../hooks/useImg";
import { goodsType, reservaSwitch } from "../../../../enums/goods";
const $data = reactive({
  localNo: "",
  orderServiceId: "",
  info: null,
  orderInfo: null,
  csphoneShow: false,
});
const showApplyBtn = computed(() => {
  if (!$data.orderInfo) return false;
  const { dyGoodsType, status, refundSwitch } = $data.orderInfo;
  // Number(status) > orderStatus.awaitReservation &&
  if (
    dyGoodsType == goodsType.reservation &&
    Number(status) > orderStatus.awaitReservation &&
    refundSwitch == reservaSwitch.on
  ) {
    return true;
  }
  return false;
});
const init = () => {
  refundOrderDetail({ localNo: $data.localNo }).then((res) => {
    if (res.code === errorCode.success) {
      $data.info = res.data;
      if ($data.info) {
        const {
          refundStatus,
          orderRefundMode,
          fastRefundMode,
          orderTotalPrice = 0,
          orderRefundPrice = 0,
        } = $data.info;
        $data.info._picurl = useImgSrc($data.info.picurl);
        $data.info._config = orderRefundStatusConfig[refundStatus] ?? {};
        // 退款渠道
        $data.info._wayConfig = orderRefundWayConfig[orderRefundMode] ?? {};
        // 加急退款渠道
        $data.info._wayJJConfig = orderRefundWayConfig[fastRefundMode] ?? {};
        // 扣款 实付金额-退款金额
        $data.info._diff = (
          Number(orderTotalPrice) - Number(orderRefundPrice)
        ).toFixed(2);
        $data.info._diff = $data.info._diff >= 0 ? $data.info._diff : 0;
        // if (isDev) {
        //   $data.info.coupon = [
        //     {
        //       userCouponId: 1, //用户优惠券id
        //       title: "测试优惠券1", //优惠券名称
        //       couponType: 1, //优惠券类型1代金券2折扣券
        //       actualPrice: 100, //【couponType=1优惠券金额=2折扣比例 】
        //       fullPrice: 0, //满减条件金额
        //       domesticServiceId: 1,
        //       startTime: "2024-12-01", //开始时间
        //       endTime: "2025-12-02", //结束时间
        //       useCity: "22", //可用城市code编码
        //       status: 1, //使用状态0=未使用1=已使用2=已过期
        //       maxUse: 0, //【couponType=2用】折扣券最大使用金额
        //       useType: "0", //限时可用0不限1周末2工作日
        //       domesticServiceTitle: "日常服务", //可用服务名称
        //       description: [
        //         "1、限用服务：日常服务",
        //         "2、限用城市:不限",
        //         "3、限用日期:不限",
        //       ],
        //     },
        //   ];
        // }
        $data.info.coupon.forEach((item) => {
          item._open = false;
          item._couponTypeName =
            couponTypeConfig[item.couponType]?.typeName ?? "";
          item._useDate = couponUseTypeConfig[item.useType]?.desc ?? "";
        });
      }
    }
  });
  getOrderDetail({
    localNo: $data.localNo,
    orderServiceId: $data.orderServiceId,
  }).then((res) => {
    if (res.code === errorCode.success) {
      $data.orderInfo = res.data;
    }
  });
};

const onSave = async () => {
  // uni.showModal({
  //   content: "确认提交?",
  //   success: async (success) => {
  //     if (success.confirm) {
  //       $data.loading = true;
  //       let can = false;
  //       if (
  //         $data.info.goodsType == goodsType.group ||
  //         ($data.info.goodsType == goodsType.reservation &&
  //           $data.refundInfo?.refundStatus == orderRefundStatus.can &&
  //           !$data.refundInfo?.douYinBookId)
  //       ) {
  //         can = true;
  //       } else {
  //         can = await cancel();
  //       }
  //       console.log("can", can);
  //       if (!can) return;
  //       const refundInfo = {
  //         reason: [$data.reasonName],
  //       };
  //       const callbackData = {
  //         localNo: $data.localNo,
  //         reasonName: $data.reasonName,
  //         orderTotalPrice: $data.douYinPayJson.total_amount, // $data.info.firstTotalPrice,
  //         reasonContent: $data.remark,
  //         img: $data.fileList.map((m) => m.file.data[0].url).join(","),
  //         phone: $data.phone,
  //         workSecondPrice: $data.workSecondPrice,
  //       };
  //       console.log("refundInfo", refundInfo);
  //       console.log("callbackData", callbackData);
  //       // console.log("skuList", [$data.douYinPayJson]);
  //       console.log("$data.douYinPayJson", $data.douYinPayJson);
  //       console.log("itemOrderList", $data.douYinPayJson?.item_order_info_list);
  //       console.log("refundAmount", $data.douYinPayJson.total_amount);
  //       const NTT = useTTPlugin();
  //       NTT.applyRefund({
  //         outOrderNo: $data.localNo,
  //         refundInfo,
  //         // skuList: $data.douYinPayJson.skuList,
  //         itemOrderList: $data.douYinPayJson.item_order_info_list, // 全额退
  //         // itemOrderDetail: $data.douYinPayJson?.item_order_detail, // 部分退
  //         // refundAmount: $data.douYinPayJson.total_amount,
  //         // refund_amount: $data.douYinPayJson.total_amount,
  //         // refundTotalAmount: $data.douYinPayJson.total_amount,
  //         callbackData,
  //         success: (success) => {
  //           console.log("退款success", success);
  //           BasicConfig.toast("提交成功");
  //           setTimeout(() => {
  //             // uni.navigateBack({
  //             //   delta: 1,
  //             // });
  //             $data.loading = false;
  //             jumpPage({
  //               to: `/package-service/pages/order/afterSales/detail`,
  //               query: {
  //                 localNo: $data.localNo,
  //               },
  //               mode: "reLaunch",
  //             });
  //           }, 1000);
  //         },
  //         fail: (fail) => {
  //           console.log("退款fail", fail);
  //           BasicConfig.toast("提交失败，请联系管理员！");
  //           $data.loading = false;
  //         },
  //       });
  //     }
  //   },
  // });
};
const cancel = async () => {
  // const { code, msg } = await cancelSubscribeOrder({
  //   localNo: $data.localNo,
  // }).catch((err) => {
  //   return Promise.resolve(false);
  // });
  // if (code !== errorCode.success) {
  //   $data.loading = false;
  //   BasicConfig.toast(msg);
  //   return Promise.resolve(false);
  // } else return Promise.resolve(true);
};

const onOpen = (e) => {
  e._open = !e._open;
};
const onCancel = () => {
  uni.showModal({
    content: "确认取消?",
    success: (success) => {
      if (success.confirm) {
        cancelRefundOrder({
          orderServiceRefundId: $data.info.orderServiceRefundId,
        }).then((res) => {
          BasicConfig.toast(res.msg);
          if (res.code === errorCode.success) {
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 1500);
          }
        });
      }
    },
  });
};
onLoad((options) => {
  $data.localNo = options.localNo;
  $data.orderServiceId = options.orderServiceId;
  init();
});
onUnload(() => {});
onReady(() => {});
</script>

<style lang="scss" scoped>
@import "../../../static/style/order/detail/common.scss";
.page {
  .status {
    padding: 30rpx;
    background: #ffffff;
    font-weight: 700;
    position: sticky;
    top: 0;
  }
  .card {
    padding: 0 30rpx;
  }
  .red {
    color: #e61111;
    font-size: 30rpx;
    padding: 30rpx 0;
  }

  .examine {
    padding: 120rpx 30rpx 100rpx 30rpx;
    background: #ffffff;
  }

  .list-item {
    position: relative;
    margin-top: 30rpx;
    border-radius: 20rpx;
    background: var(--bg-desc-color);
    .coupon {
      background: #f7f8fa;
      display: flex;
      align-items: center;
      height: 240rpx;
      .left_img {
        width: 250rpx;
        height: 100%;
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        image {
          width: 100%;
          height: 100%;
        }
        &--text {
          color: #ffffff;
          text-align: center;
          position: absolute;
          .price {
            font-size: 50rpx;
            font-weight: 700;
          }
          .desc {
            font-size: 32rpx;
            color: #ffffff;
          }
        }
      }
      .right {
        padding: 30rpx;
        width: calc(100% - 250rpx);
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        &_title {
          font-size: 34rpx;
          font-weight: 700;
        }
        &_time {
          font-size: 32rpx;
        }
        &_btn {
          color: $main-color;
          font-size: 32rpx;
          display: flex;
          align-items: center;
        }
      }
    }
    .coupon-desc {
      padding: 30rpx;
      .desc_row {
        font-size: 32rpx;
        font-weight: 700;
      }
    }
  }

  .dot {
    display: flex;
    align-items: stretch;
    &_left {
      width: 60rpx;
      position: relative;
      &::before {
        content: "";
        position: absolute;
        left: 43rpx;
        right: 0;
        top: 0;
        width: 30rpx;
        height: 30rpx;
        border-radius: 100%;
        // background: $main-color;
        border: 1px solid $main-color;
        background: #ffffff;
        z-index: 2;
      }
    }

    &_right {
      width: calc(100% - 60rpx);
      padding: 0 30rpx;
    }
    &_left--active {
      &::before {
        // content: "";
        // position: absolute;
        // left: 44rpx;
        // right: 0;
        // top: 0;
        // width: 30rpx;
        // height: 30rpx;
        // border-radius: 100%;
        background: $main-color;
        // z-index: 2;
      }
    }

    &:not(:last-child) {
      .dot_left {
        border-right: 1px solid $main-color;
      }
    }
  }
  .gap {
    height: 60rpx;
    display: flex;
    align-items: stretch;
    &_left {
      width: 60rpx;
      border-right: 1px solid $main-color;
    }

    &_right {
      width: calc(100% - 60rpx);
      padding: 0 30rpx;
    }
  }
}
</style>
